/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ws.service;

import entidade.persistencia.Manutencao;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.sun.jersey.api.core.ResourceContext;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import entidade.persistencia.EntradaSaida;
import entidade.persistencia.ProdutoManutencao;
import entidade.persistencia.Funcionario;
import entidade.persistencia.Usuario;
import java.util.List;
import ws.converter.ManutencaoConverter;

/**
 *
 * @author victorinox
 */

public class ManutencaoResource {
    @Context
    protected UriInfo uriInfo;
    @Context
    protected ResourceContext resourceContext;
    protected Integer id;
  
    /** Creates a new instance of ManutencaoResource */
    public ManutencaoResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * Get method for retrieving an instance of Manutencao identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of ManutencaoConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public ManutencaoConverter get(@QueryParam("expandLevel")
    @DefaultValue("1")
    int expandLevel) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            return new ManutencaoConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
        } finally {
            PersistenceService.getInstance().close();
        }
    }

    /**
     * Put method for updating an instance of Manutencao identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an ManutencaoConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(ManutencaoConverter data) {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            EntityManager em = persistenceSvc.getEntityManager();
            updateEntity(getEntity(), data.resolveEntity(em));
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Delete method for deleting an instance of Manutencao identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        PersistenceService persistenceSvc = PersistenceService.getInstance();
        try {
            persistenceSvc.beginTx();
            deleteEntity(getEntity());
            persistenceSvc.commitTx();
        } finally {
            persistenceSvc.close();
        }
    }

    /**
     * Returns an instance of Manutencao identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Manutencao
     */
    protected Manutencao getEntity() {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        try {
            return (Manutencao) em.createQuery("SELECT e FROM Manutencao e where e.manutencaoId = :manutencaoId").setParameter("manutencaoId", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    protected Manutencao updateEntity(Manutencao entity, Manutencao newEntity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        List<Funcionario> funcionarioCollection = entity.getFuncionarioCollection();
        List<Funcionario> funcionarioCollectionNew = newEntity.getFuncionarioCollection();
        List<EntradaSaida> entradaSaidaCollection = entity.getEntradaSaidaCollection();
        List<EntradaSaida> entradaSaidaCollectionNew = newEntity.getEntradaSaidaCollection();
        Usuario clienteId = entity.getClienteId();
        Usuario clienteIdNew = newEntity.getClienteId();
        List<ProdutoManutencao> produtoManutencaoCollection = entity.getProdutoManutencaoCollection();
        List<ProdutoManutencao> produtoManutencaoCollectionNew = newEntity.getProdutoManutencaoCollection();
        entity = em.merge(newEntity);
        for (Funcionario value : funcionarioCollection) {
            if (!funcionarioCollectionNew.contains(value)) {
                value.getManutencaoCollection().remove(entity);
            }
        }
        for (Funcionario value : funcionarioCollectionNew) {
            if (!funcionarioCollection.contains(value)) {
                value.getManutencaoCollection().add(entity);
            }
        }
        for (EntradaSaida value : entradaSaidaCollection) {
            if (!entradaSaidaCollectionNew.contains(value)) {
                value.getManutencaoCollection().remove(entity);
            }
        }
        for (EntradaSaida value : entradaSaidaCollectionNew) {
            if (!entradaSaidaCollection.contains(value)) {
                value.getManutencaoCollection().add(entity);
            }
        }
        if (clienteId != null && !clienteId.equals(clienteIdNew)) {
            clienteId.getManutencaoCollection().remove(entity);
        }
        if (clienteIdNew != null && !clienteIdNew.equals(clienteId)) {
            clienteIdNew.getManutencaoCollection().add(entity);
        }
        for (ProdutoManutencao value : produtoManutencaoCollection) {
            if (!produtoManutencaoCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from produtoManutencaoCollection"));
            }
        }
        for (ProdutoManutencao value : produtoManutencaoCollectionNew) {
            if (!produtoManutencaoCollection.contains(value)) {
                Manutencao oldEntity = value.getManutencao();
                value.setManutencao(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getProdutoManutencaoCollection().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    protected void deleteEntity(Manutencao entity) {
        EntityManager em = PersistenceService.getInstance().getEntityManager();
        for (Funcionario value : entity.getFuncionarioCollection()) {
            value.getManutencaoCollection().remove(entity);
        }
        for (EntradaSaida value : entity.getEntradaSaidaCollection()) {
            value.getManutencaoCollection().remove(entity);
        }
        Usuario clienteId = entity.getClienteId();
        if (clienteId != null) {
            clienteId.getManutencaoCollection().remove(entity);
        }
        if (!entity.getProdutoManutencaoCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because produtoManutencaoCollection is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of FuncionarioesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of FuncionarioesResource
     */
    @Path("funcionarioCollection/")
    public FuncionarioesResource getFuncionarioCollectionResource() {
        FuncionarioCollectionResourceSub resource = resourceContext.getResource(FuncionarioCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of EntradaSaidasResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of EntradaSaidasResource
     */
    @Path("entradaSaidaCollection/")
    public EntradaSaidasResource getEntradaSaidaCollectionResource() {
        EntradaSaidaCollectionResourceSub resource = resourceContext.getResource(EntradaSaidaCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of UsuarioResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioResource
     */
    @Path("clienteId/")
    public UsuarioResource getClienteIdResource() {
        ClienteIdResourceSub resource = resourceContext.getResource(ClienteIdResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    /**
     * Returns a dynamic instance of ProdutoManutencaoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ProdutoManutencaoesResource
     */
    @Path("produtoManutencaoCollection/")
    public ProdutoManutencaoesResource getProdutoManutencaoCollectionResource() {
        ProdutoManutencaoCollectionResourceSub resource = resourceContext.getResource(ProdutoManutencaoCollectionResourceSub.class);
        resource.setParent(getEntity());
        return resource;
    }

    public static class FuncionarioCollectionResourceSub extends FuncionarioesResource {

        private Manutencao parent;

        public void setParent(Manutencao parent) {
            this.parent = parent;
        }

        @Override
        protected List<Funcionario> getEntities(int start, int max, String query) {
            List<Funcionario> result = new java.util.ArrayList<Funcionario>();
            int index = 0;
            for (Funcionario e : parent.getFuncionarioCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class EntradaSaidaCollectionResourceSub extends EntradaSaidasResource {

        private Manutencao parent;

        public void setParent(Manutencao parent) {
            this.parent = parent;
        }

        @Override
        protected List<EntradaSaida> getEntities(int start, int max, String query) {
            List<EntradaSaida> result = new java.util.ArrayList<EntradaSaida>();
            int index = 0;
            for (EntradaSaida e : parent.getEntradaSaidaCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    public static class ClienteIdResourceSub extends UsuarioResource {

        private Manutencao parent;

        public void setParent(Manutencao parent) {
            this.parent = parent;
        }

        @Override
        protected Usuario getEntity() {
            Usuario entity = parent.getClienteId();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }

    public static class ProdutoManutencaoCollectionResourceSub extends ProdutoManutencaoesResource {

        private Manutencao parent;

        public void setParent(Manutencao parent) {
            this.parent = parent;
        }

        @Override
        protected List<ProdutoManutencao> getEntities(int start, int max, String query) {
            List<ProdutoManutencao> result = new java.util.ArrayList<ProdutoManutencao>();
            int index = 0;
            for (ProdutoManutencao e : parent.getProdutoManutencaoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
